package solution;

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int subarraySum(int[] nums, int k) {
        int len = nums.length;

        int[] dp = new int[len + 1];
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int count = 0;
        for (int i = 1; i < len + 1; i++) {
            dp[i] = dp[i - 1] + nums[i - 1];
            count += map.getOrDefault(dp[i] - k, 0);
            map.put(dp[i], map.getOrDefault(dp[i], 0) + 1);
        }

        return count;
    }
}